package com.ruoyi.basic.controller;

import java.io.IOException;
import java.util.List;

import com.ruoyi.api.system.domain.SysDept;
import com.ruoyi.api.system.utils.ShiroUtils;
import com.ruoyi.api.system.utils.poi.ExcelUtil;
import com.ruoyi.basic.domain.BasicImage;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.ZtreeString;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.file.ImageUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.basic.domain.BasicUser;
import com.ruoyi.basic.service.IBasicUserService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 用户基本信息Controller
 * 
 * @author ruoyi
 * @date 2021-08-19
 */
@Controller
@RequestMapping("/basic/user")
public class BasicUserController extends BaseController
{
    private String prefix = "basic/user";

    @Autowired
    private IBasicUserService basicUserService;

    @RequiresPermissions("basic:user:view")
    @GetMapping()
    public String user()
    {
        return prefix + "/user";
    }

    /**
     * 查询用户基本信息列表
     */
    @RequiresPermissions("basic:user:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(BasicUser basicUser)
    {
        startPage();
        List<BasicUser> list = basicUserService.selectBasicUserList(basicUser);
        return getDataTable(list);
    }

    /**
     * 导出用户基本信息列表
     */
    @RequiresPermissions("basic:user:export")
    @Log(title = "用户基本信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(BasicUser basicUser)
    {
        List<BasicUser> list = basicUserService.selectBasicUserList(basicUser);
        ExcelUtil<BasicUser> util = new ExcelUtil<BasicUser>(BasicUser.class);
        return util.exportExcel(list, "用户基本信息数据");
    }

    @Log(title = "用户基本信息", businessType = BusinessType.IMPORT)
    @RequiresPermissions("basic:user:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<BasicUser> util = new ExcelUtil<BasicUser>(BasicUser.class);
        List<BasicUser> userList = util.importExcel(file.getInputStream());
        String message = basicUserService.importUser(userList, updateSupport, ShiroUtils.getLoginName());
        return AjaxResult.success(message);
    }

    @RequiresPermissions("basic:user:import")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate()
    {
        ExcelUtil<BasicUser> util = new ExcelUtil<BasicUser>(BasicUser.class);
        return util.importTemplateExcel("员工基本信息");
    }

    /**
     * 新增用户基本信息
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存用户基本信息
     */
    @RequiresPermissions("basic:user:add")
    @Log(title = "用户基本信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@RequestParam(required = false) MultipartFile file, BasicUser basicUser)
    {
        try{
            String imageFile = FileUploadUtils.upload(RuoYiConfig.getUploadPath() + "/" + basicUser.getName(), file, false);
            basicUser.setUserImage(imageFile);
            basicUser.setCreateBy(ShiroUtils.getLoginName());
            return toAjax(basicUserService.insertBasicUser(basicUser));
        } catch (IOException e) {
            e.printStackTrace();
            return error("图片上传失败");
        }
    }

    /**
     * 修改用户基本信息
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        BasicUser basicUser = basicUserService.selectBasicUserById(id);
        mmap.put("basicUser", basicUser);
        if(StringUtils.isNotEmpty(basicUser.getUserImage())) {
            String filePath = RuoYiConfig.getProfile() + StringUtils.substringAfter(basicUser.getUserImage(), Constants.RESOURCE_PREFIX);
            String userImage = "data:image/files;base64," + ImageUtils.imageToBase64(filePath);
            mmap.put("userImage", userImage);
        }
        return prefix + "/edit";
    }

    /**
     * 修改保存用户基本信息
     */
    @RequiresPermissions("basic:user:edit")
    @Log(title = "用户基本信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@RequestParam(required = false) MultipartFile file, BasicUser basicUser)
    {
        try {
            if(!file.isEmpty()) {
                BasicUser old = basicUserService.selectBasicUserById(basicUser.getId());
                FileUtils.deleteFile(RuoYiConfig.getProfile() + StringUtils.substringAfter(old.getUserImage(), Constants.RESOURCE_PREFIX));

                String imageFile = FileUploadUtils.upload(RuoYiConfig.getUploadPath() + "/" + basicUser.getName(), file, false);
                basicUser.setUserImage(imageFile);
            }
            basicUser.setUpdateBy(ShiroUtils.getLoginName());
            return toAjax(basicUserService.updateBasicUser(basicUser));
        }catch (IOException e){
            e.printStackTrace();
            return error("图片上传失败");
        }
    }

    /**
     * 删除用户基本信息
     */
    @RequiresPermissions("basic:user:remove")
    @Log(title = "用户基本信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(basicUserService.deleteBasicUserByIds(ids));
    }

    /**
     * 校验工号
     */
    @PostMapping("/checkUserNoUnique")
    @ResponseBody
    public String checkUserNoUnique(BasicUser user)
    {
        return basicUserService.checkUserNoUnique(user);
    }

    /**
     * 校验工号
     */
    @PostMapping("/checkIdCardUnique")
    @ResponseBody
    public String checkIdCardUnique(BasicUser user)
    {
        return basicUserService.checkIdCardUnique(user);
    }

    /**
     * 用户同步
     */
    @RequiresPermissions("basic:user:sync")
    @Log(title = "用户同步", businessType = BusinessType.INSERT)
    @PostMapping("/syncUser")
    @ResponseBody
    public AjaxResult syncUser(String userIds)
    {
        String message = basicUserService.syncUser(userIds);
        return AjaxResult.success(message);
    }

    /**
     * 选择人员树
     *
     */
    @GetMapping("/selectTree")
    public String selectTree() {
        return prefix + "/tree";
    }

    /**
     * 选择人员树
     *
     */
    @GetMapping("/userTree")
    public String userTree() {
        return prefix + "/userTree";
    }

    /**
     * 加载人员列表树
     */
    @GetMapping("/treeData")
    @ResponseBody
    public List<ZtreeString> treeData()
    {
        List<ZtreeString> ztrees = basicUserService.selectUserTree(new SysDept());
        return ztrees;
    }
}
